package com.narata.netty.n2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

/**
 * @Author: XJL
 * @Description:
 * @Date: Create in 23:18 2022-04-27
 * @Modified By:
 **/
public class EventLoopClient {

    public static void main(String[] args) throws InterruptedException {

        // 2 带有Future， Promise的类型都是和异步方法配到使用， 用来处理结果
        ChannelFuture channelFuture = new Bootstrap().group(new NioEventLoopGroup()).channel(NioSocketChannel.class).handler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                nioSocketChannel.pipeline().addLast(new StringEncoder());
            }
            // 1 连接到服务器
            // 异步阻塞， main发起调用，真正执行connect是nio线程
        }).connect(new InetSocketAddress("localhost", 8080)); // 1s后

        // 2.1 使用sycn方法同步处理结果
//        channelFuture.sync(); // 阻塞当前线程，直到nio线程连接完毕
//        Channel channel = channelFuture.channel();
//        channel.writeAndFlush("hello world");

        // 2.2 使用addListener(回调对象)方法异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            // 在NIO线程连接建立好之后， 会调用operationComplete
            @Override
            public void operationComplete(ChannelFuture channelFuture) throws Exception {
                Channel channel = channelFuture.channel();
                channel.writeAndFlush("hello world");
            }
        });
    }
}
